//
//  ConPublicNearViewController.m
//  Shengzhuli
//
//  Created by FXGuo on 2017/7/20.
//  Copyright © 2017年 kamangkeji. All rights reserved.
//

#import "ConPublicNearViewController.h"
#import "NearPublicInfoCell.h"
#import "NearActivityProcessCell.h"
#import "CustomerInfoCell.h"
#import "ClubNetwork.h"
#import "MBProgressHUD+MJ.h"
#import "TakePhotoTool.h"
#import "SZLAccountHelper.h"
#import "ActivityDetailModel.h"
#import "CustomerModel.h"
#import "TimePickerView.h"
#import "NSDate+Extension.h"
#import "ConClubShowViewController.h"
#import "UIViewController+RTRootNavigationController.h"
#import "ConNavigationontroller.h"

@interface ConPublicNearViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView *tableView;

@end

@implementation ConPublicNearViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"编辑活动";
    if (!self.nearModel) {
        self.nearModel = [[ActivityDetailModel alloc]init];
        CustomerModel *customerModel = [[CustomerModel alloc]init];
        customerModel.isLast = YES;
        [self.nearModel.guestList addObject:customerModel];
    }else {
        CustomerModel *model = self.nearModel.guestList.lastObject;
        model.isLast = YES;
        model.isCan = YES;
    }
    [self.view addSubview:self.tableView];
    [self setNavi];
}
- (void)setNavi
{
    UIButton *saveBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 70, 30)];
    [saveBtn setTitle:@"立即发布" forState:UIControlStateNormal];
    [saveBtn setTitleColor:RGBColor(255, 121, 201) forState:UIControlStateNormal];
    saveBtn.titleLabel.font = Font(16);
    [saveBtn addTarget:self action:@selector(publickClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:saveBtn];
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2+self.nearModel.guestList.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return ScreenW*125/309+179;
    }else if (indexPath.section == 1) {
        return 160;
    }
    return 270;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        NearPublicInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([NearPublicInfoCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.nearModel;
        cell.uploadBtnClick = ^(UIButton *btn) {
            [self takePhoto:btn];
        };
        cell.showTimeBlock = ^(UITextField *field) {
            [self showTimePicker:field];
        };
        cell.isHideLeftImage = YES;
        return cell;
    }else if (indexPath.section == 1){
        NearActivityProcessCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([NearActivityProcessCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.nearModel;
        return cell;
    }
    CustomerInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CustomerInfoCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.nearModel.guestList[indexPath.section-2];
    cell.uploadBlock = ^(UIButton *upBtn, UIButton *addBtn, BOOL isHaveText,CustomerModel *model) {
        [self takeDesPhoto:upBtn addBtn:addBtn isHave:isHaveText model:model];
    };
    cell.addDeleteBlock = ^(UIButton *btn, CustomerModel *model) {
        if (btn.tag == 0) {//新增
            CustomerModel *addModel = [[CustomerModel alloc]init];
            [self.nearModel.guestList addObject:addModel];
        }else {//删除
            [self.nearModel.guestList removeObject:model];
        }
        for (NSInteger i=0; i<self.nearModel.guestList.count; i++) {
            CustomerModel *model = self.nearModel.guestList[i];
            if (i == self.nearModel.guestList.count-1) {
                model.isLast = YES;
                if ((model.avatarUrl||model.avatarImg)&&model.title) {
                    model.isCan = YES;
                }else {
                    model.isCan = NO;
                }
            }else {
                model.isLast = NO;
            }
        }
        [self.tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)]; 
        [self.tableView reloadData];
    };
    return cell;
}
- (void)showTimePicker:(UITextField *)field
{
    [self.view endEditing:YES];//键盘时间会影响window 等键盘消失了再弹出
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        TimePickerView *picker = [TimePickerView showTimerPicker];
        picker.title = @"选择时间";
        picker.minimumDate = [NSDate date];
        picker.datePickerMode = UIDatePickerModeDateAndTime;
        __WEAK
        __weak typeof(TimePickerView) *weakPicker = picker;
        picker.sureBlock = ^(NSDate *selectDate){
            field.text = [selectDate convertDateToMinusSting];
            weakSelf.nearModel.holdDate = field.text;
            [weakPicker cancel];
        };
    });
}
- (void)publickClick
{
    if (!self.nearModel.activityPictureUrl) {
        [MBProgressHUD showError:@"请补全活动图片"];
        return;
    }
    if (!self.nearModel.title) {
        [MBProgressHUD showError:@"请填写活动名称"];
        return;
    }
    if (!self.nearModel.holdDate) {
        [MBProgressHUD showError:@"请填写举办时间"];
        return;
    }
    if (!self.nearModel.address) {
        [MBProgressHUD showError:@"请填写活动地址"];
        return;
    }
    if (!self.nearModel.flow) {
        [MBProgressHUD showError:@"请填写活动流程"];
        return;
    }
    for (CustomerModel *model in self.nearModel.guestList) {
        if (!model.title || !model.avatarUrl) {
            [MBProgressHUD showError:@"请上传完整的受邀嘉宾"];
            return;
        }
    }
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"clubId"] = @(self.clubId);
    parame[@"activityPictureUrl"] = [NSString stringWithFormat:@"%@",self.nearModel.activityPictureUrl];
    parame[@"title"] = self.nearModel.title;
    parame[@"holdDate"] = self.nearModel.holdDate;
    parame[@"address"] = self.nearModel.address;
    parame[@"flow"] = self.nearModel.flow;
    if (self.nearModel.ID) {
        parame[@"id"] = @(self.nearModel.ID);
    }
    NSMutableArray *details = [NSMutableArray array];
    for (CustomerModel *model in self.nearModel.guestList) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"title"] = model.title;
        dict[@"avatarUrl"] = model.avatarUrl;
        [details addObject:dict];
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:details options:0 error:nil];
    parame[@"appGuestList"] = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    [self showClearBgWaiter];
    [ClubNetwork nearActivityAddModifyWithParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            [MBProgressHUD showSuccess:@"发布成功"];
            if (self.publicNearBlock) {
                self.publicNearBlock();
            }
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                UIViewController *vc = self.rt_navigationController.rt_viewControllers[1];
                if ([vc isKindOfClass:[ConClubShowViewController class]]) {
                    ConClubShowViewController *showVc = (ConClubShowViewController *)vc;
                    if (showVc.refreshBlock) {
                        showVc.refreshBlock(1);
                    }
                }
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}
//上传描述图片
- (void)takePhoto:(UIButton *)btn
{
    [[TakePhotoTool shareTool]beginSelectWithScale:309/125.0 image:^(UIImage *image, NSString *path) {
        [btn setImage:image forState:UIControlStateNormal];
        self.nearModel.activityPictureUrl = path;
    }];
}
//上传嘉宾
- (void)takeDesPhoto:(UIButton *)upBtn addBtn:(UIButton *)addBtn isHave:(BOOL)isHave model:(CustomerModel *)model
{
    [[TakePhotoTool shareTool]beginSelectWithScale:1.0 image:^(UIImage *image, NSString *path) {
        [upBtn setBackgroundImage:image forState:UIControlStateNormal];
        model.avatarUrl = path;
        model.avatarImg = image;
        if (isHave) {
            addBtn.enabled = YES;
            addBtn.backgroundColor = RGBColor(255, 120, 201);
        }
    }];
}
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, ScreenW, 0, 0)];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsMake(0, ScreenW, 0, 0)];
    }
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenW,ScreenH-64) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.sectionFooterHeight = 0.01;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = RGBColor(239, 239, 244);
        _tableView.tableFooterView = [[UIView alloc]init];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([NearPublicInfoCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([NearPublicInfoCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([NearActivityProcessCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([NearActivityProcessCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CustomerInfoCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([CustomerInfoCell class])];
    }
    return _tableView;
}
//取消section悬浮效果
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = 10;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

@end
